//
//  ItemViewController.m
//  iMiniTao
//
//  Created by liunian on 13-8-19.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "ItemViewController.h"
#import "WebViewController.h"
#import "FavoritManager.h"
#import "UMSocial.h"
#import "SNSManager.h"
#import "JSON.h"
#import "HeadView.h"
#import "SDImageCache.h"
#import <QuartzCore/QuartzCore.h>
#import "CommentRequest.h"
#import "Comment.h"
#import "CommentCell.h"
#import "CommentViewController.h"

#define kDefaultBottomBarHeight           38

#define BROWSER_TITLE_LBL_TAG 12731
#define BROWSER_DESCRIP_LBL_TAG 178273
#define BROWSER_LIKE_BTN_TAG 12821

@interface ItemViewController ()<UIWebViewDelegate,SNSManagerDelegate,UMSocialUIDelegate,UITableViewDataSource,UITableViewDelegate,ReqDelegate>{
}
@property (nonatomic, retain) CuzyTBKItem *item;
@property (nonatomic, retain) UIImageView          *bottomImageView;

@property (nonatomic, retain) UIButton      *commentBtn;
@property (nonatomic, retain) UIButton      *favBtn;
@property (nonatomic, retain) UIButton      *forwardBtn;
@property (nonatomic, retain) NSString      *shortenUrl;

@property (nonatomic, strong) HeadView *headView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView    *headerView;
@property (nonatomic, strong) UILabel   *nameLabel;
@property (nonatomic, strong) UILabel   *priceLabel;
@property (nonatomic, strong) UILabel   *promotionPriceLabel;
@property (nonatomic, strong) UIView    *footerView;
@property (nonatomic, strong) CommentRequest    *reqComment;
@property (nonatomic, strong) NSMutableArray    *datasource;
@property (nonatomic, strong) NSString *weiboId;
@end

@implementation ItemViewController

- (void)dealloc{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [[SNSManager sharedManager] cancelRequestForDelegate:self];
    _reqComment.delegate = nil;
    _reqComment = nil;
}

- (id)initWithMeItem:(CuzyTBKItem *)item
{
    self = [super init];
    if (self) {
        // Custom initialization
        self.item = item;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *clickURL = [@"http://" stringByAppendingFormat:@"%@", self.item.itemClickURLString];
    [[SNSManager sharedManager] covertToShotURL:clickURL withDelegate:self];
    [self.reqComment handleWeiboIdWithItemID:[NSString stringWithFormat:@"%d",[self.item.itemID integerValue]]
                                    itemName:[NSString stringWithFormat:@"#正品街#%@[撒花]",self.item.itemName]
                                       image:self.item.itemImageURLString
                                         url:clickURL
                                       price:self.item.promotionPrice
                                         tag:self.catalog
                                    delegate:self];
    [self.view addSubview:self.bottomImageView];
    [self initHeadView];
    [self.tableView reloadData];


}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self updateUI];
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          self.item.itemName, @"itemName",self.item.itemClickURLString, @"itemClickURLString", nil];
    [MobClick event:@"showProduct" attributes:dict];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)updateUI{
    if ([[FavoritManager sharedManager] isFavorit:self.item]) {
        [self.favBtn  setBackgroundImage:IMGNAMED(@"bt_unfocus.png") forState:UIControlStateNormal];
        [self.favBtn  setBackgroundImage:IMGNAMED(@"bt_focus.png") forState:UIControlStateHighlighted];
    }else{
        [self.favBtn  setBackgroundImage:IMGNAMED(@"bt_focus.png") forState:UIControlStateNormal];
        [self.favBtn  setBackgroundImage:IMGNAMED(@"bt_unfocus.png") forState:UIControlStateHighlighted];
    }
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)itemActionClick{
    NSString *clickURL = [@"http://" stringByAppendingFormat:@"%@", self.item.itemClickURLString];
    NSURL* url = [NSURL URLWithString:[clickURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    WebViewController *webVC = [[WebViewController alloc] initWithURL:url];
    [self.navigationController pushViewController:webVC animated:YES];
    
}

- (void)initHeadView{
    if (self.item) {
        _headView = [[HeadView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 320) withItem:self.item];
    }
}
- (void)commentBtnClick:(id)sender{
    if (self.weiboId == nil) {
        return;
    }
    CommentViewController *commentVC = [[CommentViewController alloc] initWithWeiboID:self.weiboId];
//    [self.navigationController presentViewController:commentVC animated:YES completion:nil];
    [self.navigationController pushViewController:commentVC animated:YES];
}

- (void)favBtnClick:(id)sender{
    if ([[FavoritManager sharedManager] isFavorit:self.item]) {
        [[FavoritManager sharedManager] removeItem:self.item];
    }else{
        [[FavoritManager sharedManager] favoritItem:self.item];
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.item.itemName, @"itemName",self.item.itemClickURLString, @"itemClickURLString", nil];
        [MobClick event:@"collectProduct" attributes:dict];
    }
    [self updateUI];
}
- (void)forwardBtnClick{
    if (self.item == nil) {
        return;
    }
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:kUmengAppKey
                                      shareText:self.item.itemName
                                     shareImage:self.shareImage
                                shareToSnsNames:nil
                                       delegate:self];
    
}

#pragma mark UMSocialUIDelegate
-(void)didSelectSocialPlatform:(NSString *)platformName withSocialData:(UMSocialData *)socialData{
    socialData.shareText = [NSString stringWithFormat:@"#正品街#%@[%@]..",socialData.shareText,self.shortenUrl];
    UMSocialUrlResource *urlRes = [[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeImage url:self.item.itemImageURLString];
    socialData.urlResource = urlRes;
    
    if (platformName == UMShareToWechatSession) {
        [UMSocialData defaultData].extConfig.title = self.item.itemName;   //分享标题，分享到朋友圈只能显示标题内容
        [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeOther; //设置为网页、音乐等其他类型
        WXWebpageObject *webObject = [WXWebpageObject object];    //初始化微信网页对象
        webObject.webpageUrl = self.shortenUrl; //设置网页的url地址
        [UMSocialData defaultData].extConfig.wxMediaObject = webObject; //设置网页对象
    }
}
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response{
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          self.item.itemName, @"itemName",self.item.itemClickURLString, @"itemClickURLString", nil];
    [MobClick event:@"ShareProduct" attributes:dict];
}
#pragma mark ItemManagerDelegate
- (void)mkManagerShortUrlDidFinishedWithShortUrl:(NSString *)shortUrl{
    if (shortUrl) {
        self.shortenUrl = shortUrl;
        BMLog(@"self.shortenUrl%@",self.shortenUrl);
        [self.reqComment handleWeiboIdWithItemID:[NSString stringWithFormat:@"%d",[self.item.itemID integerValue]]
                                        itemName:self.item.itemName
                                           image:self.item.itemImageURLString
                                             url:self.shortenUrl
                                           price:self.item.promotionPrice
                                             tag:self.catalog
                                        delegate:self];
    }else{
        NSString *clickURL = [@"http://" stringByAppendingFormat:@"%@", self.item.itemClickURLString];
        [[SNSManager sharedManager] covertToShotURL:clickURL withDelegate:self];
    }
}

#pragma mark SNSManagerDelegate
- (void)snsManagerShortenUrlDidFailFor:(OFTypeE)type{
    
}
- (void)snsManagerShortenUrlDidSuccessFor:(OFTypeE)type withResult:(id)result{
    NSDictionary *jsonDict = result;
    if (isDictWithCountMoreThan0(jsonDict)) {
        NSArray *urls = [jsonDict objectForKey:@"urls"];
        NSDictionary *resultDic = [urls lastObject];
        if ([resultDic objectForKey:@"url_short"] && [[resultDic objectForKey:@"result"] boolValue]) {
            self.shortenUrl = [resultDic objectForKey:@"url_short"];
            BMLog(@"self.shortenUrl%@",self.shortenUrl);
        }
    }
    
}
//show comment
- (void)snsManagerShowCommentDidSuccessFor:(OFTypeE)type weiboId:(NSString *)weiboId comments:(NSArray *)array{
    BMLog(@"array:%@",array);
}
- (void)snsManagerShowCommentDidFailFor:(OFTypeE)type withError:(SNSManagerErrorTypeE)error{

}
#pragma mark ReqDelegate
- (void)finishErrorReq:(id)Req errorCode:(int) errorCode message:(NSString *)message{

}
- (void)finishCommentReq:(id)Req itemId:(NSString *)itemid weiboId:(NSString *)weiboid comments:(NSArray *)comments{
    if (weiboid && [itemid isEqualToString:[NSString stringWithFormat:@"%d",[self.item.itemID integerValue]]]) {
        self.weiboId = weiboid;
        if (comments && comments.count > 0) {
            [self.datasource removeAllObjects];
            [self.datasource addObjectsFromArray:comments];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            
        }
    }
}
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        Comment *comment = [self.datasource objectAtIndex:indexPath.row];
        return [CommentCell heightWithComment:comment];
    }
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
         if (self.datasource.count == 0)
             return 38;
        return 38;
    }
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return 40;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        if (self.datasource.count == 0) {
            UILabel   *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 38.0f)];
            headLabel.textAlignment = [Util getAlign:ALIGNTYPE_CENTER];
            headLabel.font = FONT_CONTENT(18.0f);
            headLabel.textColor = COLOR_RGB(211.0f, 211.0f, 211.0f);
            headLabel.backgroundColor = COLOR_RGB(248, 248, 248);
            UIImage  *imgLine = IMGNAMED(@"bg_cell_separator_line.png");
            headLabel.text = @"暂时还没有评论";
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            UIImageView  *lineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, headLabel.bounds.size.height-imgLine.size.height, headLabel.bounds.size.width, imgLine.size.height)];
            lineView.backgroundColor = [UIColor clearColor];
            lineView.image = imgLine;
            [headLabel addSubview:lineView];
            
            return headLabel;
        }else{
            UIImageView  *lineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 38)];
            lineView.backgroundColor = [UIColor clearColor];
            lineView.image = IMGNAMED(@"note_bg_onesimilar.png");
            return lineView;
        }
        return nil;
    }
    CGFloat promotionPrice =[self.item.promotionPrice floatValue];
    [self.nameLabel setText:self.item.itemName];
    [self.promotionPriceLabel setText:[NSString stringWithFormat:@"￥%.0f",promotionPrice]];
    return self.headerView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 1) {
        return self.footerView;
    }
    return nil;
}
#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        
        return self.datasource.count;
    }
    return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        static NSString *identifier = @"comment";
        CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[CommentCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        }
        Comment *comment = [self.datasource objectAtIndex:indexPath.row];
        [cell updateComment:comment];
        return cell;
    }
    static NSString *identifier = @"item";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), 40)];
        [bg setBackgroundColor:[UIColor whiteColor]];
        [bg setImage:IMGNAMED(@"listCellBackground.png")];
        [bg setBackgroundColor:[UIColor colorWithWhite:1 alpha:0.9]];
        [cell.contentView addSubview:bg];
    }

    [cell.textLabel setBackgroundColor:[UIColor clearColor]];
    [cell.detailTextLabel setBackgroundColor:[UIColor clearColor]];
    
    return cell;
}
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - kDefaultBottomBarHeight, 320, kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = COLOR_RGB_BOTTOM;
        _bottomImageView.userInteractionEnabled = YES;
        [_bottomImageView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        [_bottomImageView addSubview:self.commentBtn];
        [_bottomImageView addSubview:self.favBtn];
        [_bottomImageView addSubview:self.forwardBtn];
        [back setBackgroundImage:IMGNAMED(@"btn_back.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_back_light.png") forState:UIControlStateHighlighted];
    }
    return _bottomImageView;
}

- (UIButton *)commentBtn{
    if (!_commentBtn) {
        UIImage *imgTop = IMGNAMED(@"btn_new_comments.png");
        _commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _commentBtn.exclusiveTouch = YES;
        _commentBtn.frame = CGRectMake(_bottomImageView.bounds.size.width- 3 *(imgTop.size.width+10), floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_commentBtn addTarget:self action:@selector(commentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_commentBtn setBackgroundImage:IMGNAMED(@"btn_new_comments.png") forState:UIControlStateNormal];
        [_commentBtn setBackgroundImage:IMGNAMED(@"btn_new_comments_light.png") forState:UIControlStateHighlighted];
    }
    return _commentBtn;
}

- (UIButton *)favBtn{
    if (!_favBtn) {
        UIImage *imgTop = IMGNAMED(@"bt_unfocus.png");
        _favBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _favBtn.exclusiveTouch = YES;
        _favBtn.frame = CGRectMake(_bottomImageView.bounds.size.width- 2 *(imgTop.size.width+10), floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_favBtn addTarget:self action:@selector(favBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_favBtn setBackgroundImage:IMGNAMED(@"bt_focus.png") forState:UIControlStateNormal];
        [_favBtn setBackgroundImage:IMGNAMED(@"bt_unfocus.png") forState:UIControlStateHighlighted];
    }
    return _favBtn;
}

- (UIButton *)forwardBtn{
    if (!_forwardBtn) {
        
        UIImage *imgTop = IMGNAMED(@"btn_forward.png");
        _forwardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _forwardBtn.exclusiveTouch = YES;
        _forwardBtn.frame = CGRectMake(_bottomImageView.bounds.size.width-imgTop.size.width-10, floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_forwardBtn addTarget:self action:@selector(forwardBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_forwardBtn setBackgroundImage:IMGNAMED(@"btn_forward.png") forState:UIControlStateNormal];
        [_forwardBtn setBackgroundImage:IMGNAMED(@"btn_forward_light.png") forState:UIControlStateHighlighted];
    }
    return _forwardBtn;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                   0,
                                                                   320,
                                                                   self.view.bounds.size.height - kDefaultBottomBarHeight) style:UITableViewStylePlain];
        [_tableView setBackgroundColor:[UIColor flatWhiteColor]];
        [_tableView setShowsVerticalScrollIndicator:NO];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        [_tableView setTableHeaderView:self.headView];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 60)];
        [_headerView setBackgroundColor:[UIColor whiteColor]];
        [_headerView addSubview:self.nameLabel];
        [_headerView addSubview:self.promotionPriceLabel];
        
        UIImageView *accView = [[UIImageView alloc] initWithFrame:CGRectMake(300, 23, 8, 13)];
        [accView setBackgroundColor:[UIColor whiteColor]];
        [accView setImage:IMGNAMED(@"search_item_indicator.png")];
        [_headerView addSubview:accView];
        
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [clickBtn setBackgroundColor:[UIColor clearColor]];
        
        [clickBtn setFrame:CGRectMake(0, 0, CGRectGetWidth(_headerView.frame), CGRectGetHeight(_headerView.frame))];
        [clickBtn addTarget:self action:@selector(itemActionClick) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:clickBtn];
    }
    return _headerView;
}
- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 40)];
        [_footerView setBackgroundColor:[UIColor clearColor]];
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [clickBtn setBackgroundColor:[UIColor clearColor]];
        
        [clickBtn setFrame:CGRectMake(0, 0, CGRectGetWidth(_footerView.frame), CGRectGetHeight(_footerView.frame))];
        [clickBtn setTitle:@"点击购买" forState:UIControlStateNormal];
        UIImage *image_normal = [IMGNAMED(@"buyButton.png") resizableImageWithCapInsets:UIEdgeInsetsMake(10, 20, 10, 20)];
        UIImage *image_highlighted = [IMGNAMED(@"buyButton_selected.png") resizableImageWithCapInsets:UIEdgeInsetsMake(10, 20, 10, 20)];
        [clickBtn setBackgroundImage:image_normal forState:UIControlStateNormal];
        [clickBtn setBackgroundImage:image_highlighted forState:UIControlStateHighlighted];
        [clickBtn setTitleColor:[UIColor flatWhiteColor] forState:UIControlStateNormal];
        [clickBtn setTitleColor:[UIColor flatGrayColor] forState:UIControlStateHighlighted];
        [clickBtn addTarget:self action:@selector(itemActionClick) forControlEvents:UIControlEventTouchUpInside];
        [_footerView addSubview:clickBtn];
    }
    return _footerView;
}

- (UILabel *)nameLabel{
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 220, 40)];
        _nameLabel.backgroundColor = [UIColor clearColor];
        _nameLabel.textColor = [UIColor blackColor];
        _nameLabel.font = FONT_CONTENT(14.0f);
        [_nameLabel setNumberOfLines:0];
        
    }
    return _nameLabel;
}

- (UILabel *)priceLabel{
    if (!_priceLabel) {
        _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(280, CGRectGetMinY(self.promotionPriceLabel.frame), 30, CGRectGetHeight(self.promotionPriceLabel.frame)) ];
        _priceLabel.backgroundColor = [UIColor clearColor];
        _priceLabel.textAlignment = ALIGN_CENTER;
        _priceLabel.textColor = [UIColor flatGrayColor];
        _priceLabel.font = FONT_CONTENT(14.0f);
        [_priceLabel setNumberOfLines:1];
    }
    return _priceLabel;
}
- (UILabel *)promotionPriceLabel{
    if (!_promotionPriceLabel) {
        _promotionPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(220, 10, 80, 40)];
        _promotionPriceLabel.backgroundColor = [UIColor clearColor];
        _promotionPriceLabel.textColor = [UIColor flatRedColor];
        _promotionPriceLabel.textAlignment = ALIGN_LEFT;
        _promotionPriceLabel.font = FONT_CONTENT(22.0f);
        [_promotionPriceLabel setNumberOfLines:1];
    }
    return _promotionPriceLabel;
}

- (CommentRequest *)reqComment{
    if (!_reqComment) {
        _reqComment = [[CommentRequest alloc] init];
    }
    return _reqComment;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _datasource;
}
@end
